/**
 * ReadWriteRoutingDataSource.java 2016年11月15日 11:26
 * <p>
 * Copyright (c) 2010-2016 yinghezhong Inc. All rights reserved.
 *
 * @Description
 * @version 1.0
 */
package com.ql.cloud.framework.config.dao.config.datasource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 多数据源切换
 *
 * @author 齐龙
 * @date 2016年11月15日 11:26
 *
 */
public class ReadWriteRoutingDataSource extends AbstractRoutingDataSource {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private final int readDataSourceCount;
    /* 这是线程安全的 */
    private AtomicInteger counter = new AtomicInteger(0);

    public ReadWriteRoutingDataSource(int readDataSourceCount) {
        this.readDataSourceCount = readDataSourceCount;
    }

    @Override
    protected Object determineCurrentLookupKey() {
        if (ReadWriteDataSourceDecision.isChoiceWrite()) {
            logger.debug("[DataSource]:选择writeDataSource");
            return ReadWriteDataSourceDecision.DataSourceType.write;
        }
        // 如果没有选择，则默认选择写库
        if (ReadWriteDataSourceDecision.isChoiceNone()) {
            logger.debug("no choice read/write, default determine write datasource");
            return ReadWriteDataSourceDecision.DataSourceType.write;
        }
        // 按照顺序选择读库
        // TODO 算法改进
        /**
         * counter.incrementAndGet()==(i++)
         * */
        int i = counter.incrementAndGet();

        int index = i % readDataSourceCount;
        if (index < 0) {
            index = -index;
        }
        logger.debug("[DataSource]:选择readDataSource{}", index);
        return new Integer(index);
    }

    public int getReadDataSourceCount() {
        return readDataSourceCount;
    }

}
